﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace SilverlightHVP.ViewModel
{
   public class LinksViewModel : INotifyPropertyChanged
   {
      private State state;

      private ObservableCollection<Link> allLinks;


      public LinksViewModel( State s )
      {
         state = s;
         state.CurrentItemChanged +=
            new State.CurrentItemChangedHandler( StateChanged );
         state.StateChanged += new State.StateChangedHandler( StateChanged );
         state.PositionChanged += new State.PositionChangedHandler( StateChanged );
         NotifyPropertyChanged( "Links" );
      }

      public ObservableCollection<Link> Links
      {
         get { return GetVisibleLinks(); }
      }



      private ObservableCollection<Link> GetVisibleLinks()
      {
         var visibleLinks = new ObservableCollection<Link>();
         if ( allLinks != null )
         {

            foreach ( Link link in allLinks )
            {
               if ( link.TimeToWatchFor < state.Position )
               {
                  visibleLinks.Add( link );

               }
            }
         }
         return visibleLinks;
      }

      public Link CurrentLink
      {
         get { return null; }
         set
         {
            if ( value != null )
               state.CurrentLink = value;
         }
      }


      void StateChanged( object sender, EventArgs e )
      {
         allLinks = state.Links;
         NotifyPropertyChanged( "Links" );
      }
      public event PropertyChangedEventHandler PropertyChanged;
      private void NotifyPropertyChanged( string propName )
      {
         if (PropertyChanged != null )
         {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
         }
      }

   }
}
